package com.effectivsocial.extension.plugin;

import java.io.File;
import java.io.FileReader;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;

import com.effectivsocial.service.api.LovService;

import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;



@Named
@Slf4j
public class LovValidatorLoaderPlugin implements StartupPlugin {
	@Value("#{props['data.dir']}")
	private String dataFolder;

	private final String LOV_ENTITY_PACKAGE = "com.effectivsocial.domain";

	private final String columns[] = { "name" };

	@Inject
	private LovService lovService;

	public void preProcess(ApplicationContext ctx) {
		log.info("######## Data dir = {}", dataFolder);

	}

	public void process(ApplicationContext ctx) {
		File dir = new File(dataFolder);
		File files[] = dir.listFiles();
		for (File file : files) {
			log.info("file - {}", file);
			loadLovData(file);
		}

	}


	private void loadLovData(File file) {
		String fileName = file.getName();

		log.info("Data file - {}", fileName);

		String classname = LOV_ENTITY_PACKAGE + "."
				+ StringUtil.remove(fileName, ".txt");

		log.info("Lov - {}", classname);

		ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
		List entities = null;
		try {
			strategy.setType(Class.forName(classname));
			strategy.setColumnMapping(columns);
			CsvToBean csv = new CsvToBean();
			entities = csv.parse(strategy, new FileReader(file));

			log.info("Entities to be loaded - {}", entities.size());

			lovService.checkAndLoad(entities,
					StringUtil.remove(fileName, ".txt"));

		} catch (Exception e) {
			log.error("Error", e);
		}

	}

	public void postProcess(ApplicationContext ctx) {
		// TODO Auto-generated method stub

	}

	public int getOrder() {
		return 300;
	}

}
